from tortoise.models import Model
from tortoise import fields
from typing import Dict, Any
import json


class DetectionRecord(Model):
    """检测记录模型"""
    
    id = fields.IntField(pk=True, description="记录ID")
    images_info = fields.JSONField(description="多张图片信息JSON格式，包含头顶面、头侧面、头后面三张照片")
    result = fields.JSONField(null=True, description="AI检测结果(BASP分型、严重程度、建议等JSON格式)")
    is_valid = fields.BooleanField(default=False, description="检测结果是否有效（包含完整的BASP分型、描述、建议）")
    created_at = fields.DatetimeField(auto_now_add=True, description="检测时间")
    
    # 外键关系
    user = fields.ForeignKeyField(
        "models.User", 
        related_name="detection_records",
        on_delete=fields.CASCADE,
        description="关联用户"
    )
    
    class Meta:
        table = "detection_records"
        table_description = "检测记录表"
        ordering = ["-created_at"]  # 按创建时间倒序
    
    def __str__(self):
        return f"DetectionRecord(id={self.id}, user_id={self.user_id})"
    
    @property
    def result_dict(self) -> Dict[str, Any]:
        """获取结果字典"""
        if isinstance(self.result, str):
            try:
                return json.loads(self.result)
            except json.JSONDecodeError:
                return {}
        return self.result or {}
    
    @property
    def images_dict(self) -> list:
        """获取图片信息列表"""
        if isinstance(self.images_info, str):
            try:
                return json.loads(self.images_info)
            except json.JSONDecodeError:
                return []
        return self.images_info or []
    
    @property
    def image_url(self) -> str:
        """获取主图片URL（向后兼容，返回第一张图片）"""
        images = self.images_dict
        if images and len(images) > 0:
            return images[0].get('image_url', '')
        return ''
    
    @property
    def basp_type(self) -> str:
        """获取BASP分型结果"""
        return self.result_dict.get("baspType", "")
    
    @property
    def severity(self) -> str:
        """获取脱发严重程度"""
        return self.result_dict.get("severity", "")
    
    @property
    def confidence(self) -> float:
        """获取检测置信度"""
        return self.result_dict.get("confidence", 0.0)
    
    def set_result(self, basp_type: str, severity: str, description: str, 
                   suggestion: str, confidence: float):
        """设置检测结果"""
        self.result = {
            "baspType": basp_type,
            "severity": severity,
            "description": description,
            "suggestion": suggestion,
            "confidence": confidence
        }
        # 自动检查结果有效性
        self.is_valid = self._check_result_validity()
    
    def _check_result_validity(self) -> bool:
        """检查检测结果是否有效"""
        if not self.result:
            return False
        
        result_dict = self.result_dict
        required_fields = ["baspType", "severity", "description", "suggestion"]
        
        # 检查必需字段是否存在且不为空
        for field in required_fields:
            value = result_dict.get(field, "")
            if not value or (isinstance(value, str) and value.strip() == ""):
                return False
        
        # 检查BASP分型是否有效
        basp_type = result_dict.get("baspType", "")
        valid_basp_types = ["I型", "II型", "III型", "IV型", "V型", "VI型", "VII型"]
        if basp_type not in valid_basp_types:
            return False
        
        return True
    

        return self.is_valid